/**
 * 抵扣设置 tab
 */
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { Popconfirm, Popover, Badge, Icon, message, Radio } from 'antd'
import { messages } from "share/common"
import errorMessage from 'share/errorMessage'
import SlideFrameDetail from './deduction-setting-detail'
import TableList from '../table-list'
import settingService from '../request-and-expense-settings.service'
import {batchOperations} from "components/template/wrapped-table-params/batch-operations";

const RadioGroup = Radio.Group;

class DeductionSetting extends Component {

  state = {
    loading: false,
  };

  infoData = {
    dataSource: { explain: messages('expense-4.key17')/*您可在此页面设置抵扣相关的规则（包括分摊金额取值逻辑、费用原币税额计算逻辑）*/ },
    attributes: [{ title: messages('expense-4.key18')/*说明*/, dataIndex: 'explain', span: 24 }]
  };

  slideFrameInfo = {
    title: messages('expense-4.key16')/*抵扣设置*/,
    content: SlideFrameDetail
  };

  popoverContent = (
    <div>
      {messages('expense-4.key1')/*足额报销：若发票金额=100元，关联费用（无其他发票）的费用金额等于100元*/} <br/>
      {messages('expense-4.key2')/*不足额报销：若发票金额=100元，关联费用（无其他发票）的费用金额小于100元*/} <br/>
      {messages('expense-4.key3')/*超额报销：若发票金额=100元，关联费用（无其他发票）的费用金额大于100元（系统默认不允许超额报销。允许超额报销，请至【费控标准-费用管控】页面配置“费用金额与发票价税合计总和校验”为“不校验”），超额报销时，费用原币金额等于发票税额总和*/}
    </div>
  );

  defaultInfo = {
    title: messages('expense-4.key16')/*抵扣设置*/,
    data: [{
      title: messages('expense-4.key16')/*抵扣设置*/,
      titleStyle: { marginTop: 0 },
      label: messages('expense-4.key8')/*分摊总金额取值逻辑*/,
      value: messages('expense-4.key5')/*费用原币金额*/,
      extra: (
        <div>
          {messages('expense-4.key9')/*配置费用关联可抵扣的发票时，分摊总金额取值逻辑。*/} <br/>
          {messages('expense-4.key10')/*为“费用金额”，按照费用金额分摊；*/} <br/>
          {messages('expense-4.key11')/*为“费用原币金额”，按照费用原币金额分摊。费用不关联发票以及关联不可抵扣的发票，均按照费用金额分摊*/}
        </div>
      )
    }, {
      label: (
        <div>
          {messages('expense-4.key12')/*费用原币税额计算逻辑*/}
          <Popover content={this.popoverContent}>
            <Icon type="info-circle-o" style={{ marginLeft: 5 }}/>
          </Popover>
        </div>
      ),
      value: messages('expense-4.key7')/*按比例折算*/,
      extra: (
        <div>
          {messages('expense-4.key13')/*配置发票不足额报销时，是否做全额抵扣。*/} <br/>
          {messages('expense-4.key14')/*为“全额”，费用原币税额等于关联发票税额总和；*/} <br/>
          {messages('expense-4.key15')/*为“按比例折算”，费用原币税额=费用金额/关联发票价税合计总和*关联发票税额总和*/}
        </div>
      )
    }]
  };

  searchForm = [{
    id: 'levelCode',
    dataIndex: 'levelCode',
    label: messages('expense-4.key19')/*层级*/,
    component: (
      <RadioGroup>
        <Radio value="COMPANY">{messages('expense-4.key20')/*公司*/}</Radio>
        <Radio value="TENANT">{messages('expense-4.key21')/*租户*/}</Radio>
      </RadioGroup>
    ),
    tagParser: value => {
      return value === "COMPANY" ? messages('expense-4.key20')/*公司*/ : messages('expense-4.key21')/*租户*/;
    }
  }, {
    id: 'distLevelOrgIds',
    dataIndex: 'distLevelOrgName',
    label: messages('expense-4.key22')/*启用公司*/,
    component: 'Chooser',
    props: {
      labelKey: 'name',
      valueKey: 'id',
      type: 'priority_company'
    },
    parser: value => ({
      distLevelOrgIds: value ? value.map(item => item.id) : null
    })
  }];

  columns = [{
    title: messages('expense-4.key19')/*层级*/,
    dataIndex: 'levelCode',
    render: value => value === 'COMPANY' ? messages('expense-4.key20')/*公司*/ : messages('expense-4.key21')/*租户*/
  }, {
    title: messages('expense-4.key23')/*所属组织*/,
    dataIndex: 'levelOrgName',
    render: value => <Popover content={value} placement="topLeft">{value}</Popover>
  }, {
    title: messages('expense-4.key22')/*启用公司*/,
    dataIndex: 'distLevelOrgName',
    render: value => <Popover content={value} placement="topLeft">{value}</Popover>
  }, {
    title: messages('common.column.status')/*状态*/,
    dataIndex: 'enabled',
    width: '10%',
    render: value => (
      <Badge
        status={value ? 'success' : 'error'}
        text={value ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
      />
    )
  }, {
    title: messages('common.operation')/*操作*/,
    dataIndex: 'deductionOptId',
    width: '10%',
    render: (value, record) => (
      record.readOnly ? (
        <span onClick={e => e.stopPropagation()} className="font-disabled">{messages('common.delete')/*删除*/}</span>
      ) : (
        <Popconfirm
          title={messages('common.confirm.delete')/*确定要删除吗？*/}
          onConfirm={() => this.handleDelete(value)}
        >
          <a onClick={e => e.stopPropagation()}>{messages('common.delete')/*删除*/}</a>
        </Popconfirm>
      )
    )
  }];

  handleDelete = id => {
    this.setState({ loading: true });
    return settingService.deleteDeductionSetting([id]).then(() => {
      this.setState({ loading: false });
      this.advancedTableRef.getList();
      message.success(messages('common.delete.success',{arg1: ''})/*{arg1} 删除成功*/);
    }).catch(e => {
      this.setState({ loading: false });
      errorMessage(e.response);
    })
  };

  service = (page, size, searchParams) => {
    return settingService.getDeductionSetting(page, size, searchParams);
  };

  render() {
    const { loading } = this.state;
    let tableParams =  batchOperations({
      rowKey: 'deductionOptId'
    }, [{
      type: 'DELETE',
      service: settingService.batchDeleteDeductionSetting,
      onOk: () => this.advancedTableRef.getList()
    }, {
      type: 'ENABLE',
      service: settingService.batchOpenOrCloseDeductionSetting,
      onOk: () => this.advancedTableRef.getList()
    }, {
      type: 'DISABLE',
      service: settingService.batchOpenOrCloseDeductionSetting,
      onOk: () => this.advancedTableRef.getList()
    }], this);
    return (
      <TableList
        infoData={this.infoData}
        slideFrameInfo={this.slideFrameInfo}
        defaultInfo={this.defaultInfo}
        afterClose={refresh => typeof refresh === 'boolean' && refresh && this.advancedTableRef.getList()}
        tableParams={{
          tableName: 'deduction-setting-table',
          loading,
          rowKey: 'deductionOptId',
          searchForm: this.searchForm,
          columns: this.columns,
          service: this.service,
          onRef: ref => this.advancedTableRef = ref,
          ...tableParams
        }}
      />
    )
  }
}

function mapStateToProps(state) {
  return { }
}

export default connect(mapStateToProps)(DeductionSetting)
